import { defineStore } from 'pinia'
import dayjs from 'dayjs'

export const useSimpleQueryStore = defineStore('simpleQuery', {
	state: () => ({
		// 表单数据
		formData: {
			id: '',
			dataConnectorId: '',
			itemConfig: {
				// 驼峰转换状态
				enableCamelCase: false,
				// 选中的列
				selectedColumns: [],
				// 格式化配置
				formatConfig: [],
				// 表格列定义
				columns: [],
				// 表名
				tableName: '',
				// 查询条件
				conditions: [],
				// 排序
				sorts: []
			}
		}
	}),
	getters: {
		// 获取格式化后的列标题
		getFormattedColumnTitle: (state) => (col) => {
			const formatRule = state.formData.itemConfig.formatConfig?.find(
				(c) => c.field === col.key && c.type === 'fieldname'
			)
			return formatRule ? formatRule.format : col.title
		},
		// 获取表格列配置
		getTableColumns: (state) => {
			return (state.formData.itemConfig.columns || [])
				.filter((col) => state.formData.itemConfig.selectedColumns.includes(col.key))
				.map((col) => ({
					...col,
					title: state.getFormattedColumnTitle(col) || col.title
				}))
		}
	},
	actions: {
		// 设置驼峰转换状态
		setEnableCamelCase(value) {
			this.formData.itemConfig.enableCamelCase = value
		},
		// 设置选中的列
		setSelectedColumns(columns) {
			this.formData.itemConfig.selectedColumns = columns
		},
		// 设置格式化配置
		setFormatConfig(config) {
			this.formData.itemConfig.formatConfig = config
		},
		// 设置表格列定义
		setColumns(columns) {
			this.formData.itemConfig.columns = columns
		},
		// 设置表名
		setTableName(name) {
			this.formData.itemConfig.tableName = name
			this.formData.config.tableName = name
		},
		// 设置查询条件
		setConditions(conditions) {
			this.formData.itemConfig.conditions = conditions
			this.formData.config.conditions = conditions
		},
		// 设置表单数据
		setFormData(data) {
			if (data) {
				this.formData = {
					...data,
					config: {
						tableName: data.config?.tableName || '',
						fields: data.config?.fields || [],
						conditions:
							data.config?.conditions?.map((condition) => ({
								field: condition.field,
								operator: condition.operator,
								value: condition.value
							})) || []
					},
					itemConfig: data.itemConfig || {
						enableCamelCase: false,
						selectedColumns: [],
						formatConfig: [],
						columns: [],
						tableName: '',
						conditions: []
					}
				}
			}
		},
		// 应用格式化规则
		applyFormat(value, config) {
			if (!value || !config) return value

			switch (config.type) {
				case 'datetime':
					return dayjs(value).format(config.format)
				case 'mask':
					switch (config.format) {
						case '手机号':
							return value.toString().replace(/(d{3})d{4}(d{4})/, '$1****$2')
						case '身份证号':
							return value.toString().replace(/(d{6})d{8}(w{4})/, '$1********$2')
						case '银行卡号':
							return value.toString().replace(/(d{4})d+(d{4})/, '$1 **** **** $2')
						default:
							return value
					}
				default:
					return value
			}
		}
	}
})
